import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';
import { AgentLevelService } from '@core/routes-services/agent-level.service';
import { AgentService } from '@core/routes-services/agent.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { mobileValidate } from '@core/util/formControl-validate-utils';
import { AgentListComponent } from '../agent-list.component';
import { myValidNull } from '@core/util/string-utils';

@Component({
  selector: 'app-agent-detail',
  templateUrl: './agent-detail.component.html',
  styles: [`
    h2 {
      border-bottom: 1px solid #1890ff;
      color: #1890ff;
      padding-top: 10px;
    }
  `],
})
export class AgentDetailComponent implements OnInit {

  id: any = 0;
  entity: any = {};
  isLoading: boolean = false;

  validateForm: FormGroup;
  levelOptions: any [] = [];
  parentsOptions: any [] =[];
  allOptions: any [] = [];

  @ViewChild('child')
  child:AgentListComponent;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private agentService: AgentService,
    private fb: FormBuilder,
    private agentLevelService: AgentLevelService,
    public message: NzMessageService,
  ) {
  }

  ngOnInit(): void {
    this.initLevelOptions();
    this.route.queryParams.forEach((params: Params) => {
      this.id = +params['id'];
      this.initEntity();
    });

  }
  initValidateForm(){
    this.validateForm = this.fb.group({
      name: [this.entity.name, [Validators.required, Validators.maxLength(60)]],
      phone: [this.entity.phone, [Validators.required, mobileValidate]],
      idNumber: [this.entity.idNumber, []],
      levelId: [this.entity.levelId, [Validators.required]],
      parentId: [this.entity.parentId, []],
    });
    this.filterParentOptions()
  }

  initLevelOptions() {
    this.agentLevelService.getAll().then((res) => {
      if (res.status.toString().startsWith('20')) {
        this.levelOptions = res.data.agentLevelsList;
      } else {
        this.message.warning(res.message);
      }
    }, error => {
      this.message.error(error.message ? error.message : error.error);
    });
  }

  initEntity() {
    this.isLoading = true;
    this.agentService.detail(this.id).then((res) => {
      console.log(res);
      if (res.status.toString().startsWith('20')) {
        this.entity = res.data.agent;
        this.allOptions = res.data.agentOptions;
        this.initValidateForm();
      } else {
        this.message.warning(res.message);
      }
      this.isLoading = false;
    }, error => {
      this.message.error(error.message ? error.message : error.error);
      this.isLoading = false;
    });
  }

  filterParentOptions() {
    this.parentsOptions = this.allOptions;
  }

  submitForm(): void {
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    } else {
      if(this.validateForm.value.levelId == 4 || this.validateForm.value.levelId == 5){
        // 市级和区级渠道身份证必填
        if(myValidNull(this.validateForm.value.idNumber)){
          this.message.warning("身份证号不能为空");
          return;
        }
      }
      this.isLoading = true;
      this.agentService.saveOrUpdateEntity(this.entity.id, this.validateForm.value).then((res) => {
        if (res.status.toString().startsWith('20')) {
          this.message.success("保存成功");
        } else {
          this.message.warning(res.message);
        }
        this.isLoading = false;
      }, error => {
        this.message.error(error.message ? error.message : error.error);
        this.isLoading = false;
      });
    }
  }

  goBack(){
    this.router.navigate(['/agent/list'])
  }
}
